package com.sdruixinggroup.mondayb2b.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Check;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME_ERROR;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.intoLogin;

/**
 * Created by tangjie on 2017/11/12.
 */

public class CheckActivity extends BaseActivity {
    @BindView(R.id.topbar_left)
    ImageView topbarLeft;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_check)
    TextView tvCheck;
    @BindView(R.id.tv_result)
    TextView tvResult;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.topbar_left)
    public void onClick() {
        finish();
    }

    @OnClick(R.id.tv_check)
    public void onClickCheck() {
        String sn =etCode.getText().toString().trim();
        if(!TextUtils.isEmpty(sn)){
            queryData(sn);
        }

    }

    private void queryData(String sn){
        String url = API.GOODS_UNIQUE_SN+sn +"&access_token="+ UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String,String> headers = new HashMap<>();
        headers.put("Accept","*/*");
        TypeToken<Check> typeToken =new TypeToken<Check>(){};

        OkHttpUtils.post().url(url).headers(headers).build().execute(new ObjectCallBack<Check>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(Check response, int id) {
                if(response.getErr_code() == 0){
                    String msg = "已查询 " + response.getResult().getQuery_count()+" 次,本产品是瑞星集团出品";
                    tvResult.setText(msg);
                }else  if(response.getErr_code() == TOKEN_OUT_TIME ||response.getErr_code() == TOKEN_OUT_TIME_ERROR){
                    intoLogin(CheckActivity.this);
                }else {
                    showToast(response.getErr_msg());
                }
            }
        });
    }
}
